package web.server.parameter.analysis;

import cn.hutool.http.ContentType;
import io.netty.buffer.ByteBufUtil;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import web.server.io.handler.http.WebHandler;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Request {
    private static final Logger log = LoggerFactory.getLogger(Request.class);

    private FullHttpRequest fullHttpRequest;
    private Map<String, String> headers = new HashMap<>();

    public Request(FullHttpRequest fullHttpRequest) {
        if (fullHttpRequest == null) {
            throw new IllegalArgumentException("fullHttpRequest null");
        }
        this.fullHttpRequest = fullHttpRequest;
        for (Map.Entry<String, String> entry : fullHttpRequest.headers().entries()) {
            this.headers.put(entry.getKey(), entry.getValue());
        }
    }

    public String getContentType() {
        return headers.get("Content-Type");
    }

    public String getContent() {
        if (Objects.equals(ContentType.JSON.getValue(), getContentType())) {
            if (this.fullHttpRequest.content().isReadable()) {
                byte[] bytes = ByteBufUtil.getBytes(this.fullHttpRequest.content());
                return new String(bytes, StandardCharsets.UTF_8);
            }
        }
        return "{}";
    }
}
